package work.xiaohong.gupiao.controller;

import com.alibaba.fastjson.JSON;
import work.xiaohong.gupiao.pojo.Baoxian;
import work.xiaohong.gupiao.pojo.Chart;
import work.xiaohong.gupiao.pojo.HttpResult;
import work.xiaohong.gupiao.service.BaoxianService;
import work.xiaohong.gupiao.time.HttpUtil;
import work.xiaohong.gupiao.util.UrlUtil;
import entity.Result;
import entity.StatusCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Tag(name = "Baoxian接口文档")
@RestController
@RequestMapping("/baoxian")
@CrossOrigin
public class BaoxianController {

    @Autowired
    private BaoxianService BaoxianService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static String redisName = "保险主题";
    private static String code = "1399809"; //股票代码

    static {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(date);
        redisName = redisName+format;
    }

    /**
     *
     * @param mday 时间段天数
     * @param fday 预测天使
     * @return
     */
    @GetMapping("/{mday}/{fday}")
    public Result<Chart> forecast(@PathVariable(value = "mday") int mday,@PathVariable(value = "fday") int fday) throws ParseException {


        // 判断redis里是否有数据
        if (redisTemplate.boundHashOps(redisName).get(mday*10+fday) != null){
            return new Result<Chart>(true,StatusCode.OK,"查询成功",
                    JSON.parseObject(redisTemplate.boundHashOps(redisName).get(mday*10+fday).toString(),Chart.class));
        }

        // 获取所有数据
        List<Baoxian> all = BaoxianService.findAll();
        // 获取模型天数据
        List<Baoxian> mDay = new ArrayList<>();
        for (int i = mday; i > 0 ; i--) {
            mDay.add(all.get(all.size()-i));
        }
        // 查找最匹配项
        Integer result = find(all, mDay, mday);
        if (result == -1){
            return new Result<Chart>(true,StatusCode.NOTFOUNDERROR,"没有匹配结果");
        }

        Chart chart = new Chart();
        Float mMax = 0F;
        Float mMin = Float.MAX_VALUE;
        Float fMax = 0F;
        Float fMin = Float.MAX_VALUE;
        ArrayList<String> mdate = new ArrayList<>();
        ArrayList<String> fdate = new ArrayList<>();
        ArrayList<Float> mdata = new ArrayList<>();
        ArrayList<Float> fdata = new ArrayList<>();

        for (int i = 0; i < mday; i++) {
            Float price = Float.valueOf(mDay.get(i).get收盘价().replace(",","").equals("None") ? "0" :mDay.get(i).get收盘价().replace(",",""));
            if (price > mMax){
                mMax = price;
            }
            if (price < mMin){
                mMin = price;
            }
            mdate.add(mDay.get(i).get日期());
            mdata.add(price);
        }

        for (int i = 0; i < fday+mday; i++) {
            Float price = Float.valueOf(all.get(result + i).get收盘价().replace(",","").equals("None") ? "0" : all.get(result + i).get收盘价().replace(",",""));
            if (price > fMax){
                fMax = price;
            }
            if (price < fMin){
                fMin = price;
            }
            fdate.add(all.get(result+i).get日期());
            fdata.add(price);
        }
        chart.setMdata(mdata);
        chart.setFdata(fdata);
        chart.setmMax(((int) Math.ceil(mMax) / 10 ) *10 +10);
        chart.setmMin(((int) Math.ceil(mMin) / 10 ) *10 -10);
        chart.setMdate(mdate);
        chart.setFdate(fdate);
        chart.setfMax(((int) Math.ceil(fMax) / 10 ) *10 +10);
        chart.setfMin(((int) Math.ceil(fMin) / 10 ) *10 -10);
        // 将结果存入redis
        redisTemplate.boundHashOps(redisName).put(mday*10+fday, JSON.toJSONString(chart));
        return new Result<Chart>(true,StatusCode.OK,"查询成功",chart);
    }


    public Integer find(List<Baoxian> all,List<Baoxian> mDay,int mday) {
        // 获取均值
        float sum = 0;
        for (Baoxian Baoxian : mDay) {
            sum += Float.valueOf(Baoxian.get涨跌幅().equals("None") ? "0" :Baoxian.get涨跌幅());
        }
        float avg = sum/mday;

        int resultIndex = -1;
        float resultSub = 100F;
        float sumSub = 0F;
        // 寻找最佳结果id
        for (int i = 0; i < all.size()-1-mday; i++) {
            for (int j = 1; j < mday; j++) {
                Float fd = Float.valueOf(all.get(i+j).get涨跌幅().equals("None") ? "0" : all.get(i+j).get涨跌幅());
                Float md = Float.valueOf(mDay.get(j).get涨跌幅().equals("None") ? "0" : mDay.get(j).get涨跌幅());
                if (fd*md < 0){
                    break;
                }else if (j == mday-1){
                    sumSub += fd;
                    float abs = Math.abs(avg - sumSub / j);
                    if (abs < resultSub){
                        resultSub = abs;
                        resultIndex = i;
                    }
                    sumSub = 0F;
                }else {
                    sumSub += fd;
                }
            }
        }
        return resultIndex;
    }


    /**
     * 添加或更新数据
     * @return
     */
    @Operation(summary = "添加Baoxian",description = "所需权限：")
    @GetMapping
    public Result add(){

        String url = UrlUtil.creatUrl(code, 8);
        try {
            HttpResult httpResult = HttpUtil.sendGetReq(url, null, "utf-8",null,null);
            // 先查询数据库
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date parse = simpleDateFormat.parse(httpResult.getTime());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String ft = format.format(parse);

            Baoxian st = new Baoxian();
            st.set日期(ft);
            List<Baoxian> list = BaoxianService.findList(st);
            if (list.size() != 0){
                // 更新数据库
                Baoxian Baoxian = list.get(0);
                Baoxian.set收盘价(httpResult.getPrice()+"");
                Baoxian.set涨跌幅(Double.parseDouble(httpResult.getPercent())*100 + "");
                BaoxianService.update(Baoxian);
                // 清空redis
                redisTemplate.delete(redisName);
                return new Result(true, StatusCode.OK, "更新成功", Baoxian);
            }else {
                // 添加数据库
                Baoxian Baoxian = new Baoxian();
                Baoxian.set名称(httpResult.getName());
                Baoxian.set日期(ft);
                Baoxian.set收盘价(httpResult.getPrice()+"");
                Baoxian.set涨跌幅(Double.parseDouble(httpResult.getPercent())*100 + "");
                BaoxianService.add(Baoxian);
                return new Result(true, StatusCode.OK, "添加成功", Baoxian);
            }
        }
        catch (Exception e) {
            e.printStackTrace ();
            return new Result(true,StatusCode.ERROR,"添加失败");
        }





//        // 补充日期
//        Date date = new Date();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String format = simpleDateFormat.format(date);
//        Baoxian.set日期(date);
//        Baoxian Baoxian1 = new Baoxian();
//        Baoxian1.set日期(date);
//        List<Baoxian> list = BaoxianService.findList(Baoxian1);
//        //查询是否已添加
//        if (list != null && list.size() > 0){
//            // 已添加过了，执行更新操作
//            Baoxian.setId(list.get(0).getId());
//            //调用BaoxianService实现添加Baoxian
//            BaoxianService.update(Baoxian);
//            // 清空redis
//            Set keys = redisTemplate.boundHashOps(redisName).keys();
//            for (Object key : keys) {
//                redisTemplate.boundHashOps(redisName).delete(key);
//            }
//            return new Result(true,StatusCode.OK,"更新成功");
//        }
//        else {
//            // 执行增加操作
//            //调用BaoxianService实现添加Baoxian
//            BaoxianService.add(Baoxian);
//            // 清空redis
//            Set keys = redisTemplate.boundHashOps(redisName).keys();
//            for (Object key : keys) {
//                redisTemplate.boundHashOps(redisName).delete(key);
//            }
//            return new Result(true,StatusCode.OK,"添加成功");
//        }
    }


    public static void main(String[] args) {
        String s = "18,324.97";
        System.out.println(Float.valueOf(s.replace(",","")));
    }

}
